// pages/index/index.js
import * as request from "../../utils/request/file/file.js"
import * as request1 from "../../utils/request/file/favourFile.js"
import * as request2 from "../../utils/request/folder/index"
import {
  file
} from "../../utils/request/request.js"
Page({

  /**
   * 页面的初始数据
   */

  data: {
    loadingMore: false,
    loading: false,
    value: '',
    file: [],
    current: 1,
    pageSize: 600,
    loadText: '',
    hasMore: true,
    hasShow: false,
    fatherType: '',
    search: false,
    folderList: [],
    fatherTypeArr: [],
    go: false,
    
  },
  // onReachBottom: function () {

  //   if (!this.data.hasMore) {
  //     this.setData({
  //       loadingMore: true,
  //       loadText: "没有更多了"
  //     });
  //     setTimeout(() => {
  //       this.setData({
  //         loadingMore: false,
  //       });
  //     }, 800)
  //     return;
  //   }
  //   this.setData({
  //     loadingMore: true,
  //     loadText: "加载更多..."
  //   });
  //   let current = this.data.current + 1
  //   this.setData({
  //     current: current
  //   })
  //   this.getfileInfo()
  // },
  preventDefault: function (e) {
    // 阻止触摸事件的默认行为，防止滚动  
    console.log(e)
    e.stopPropagation();
    e.preventDefault();
  },
  async openDOCX(event) {
    // wx.navigateTo({
    //   url: `/pages/index/article?id=${param}`,
    // })
    let self = this
    let key = event.currentTarget.dataset.key
    const param = event.currentTarget.dataset.param
    let targetFile = this.data.file
   
    if (targetFile[key].fileIlk == "pdf") {
      wx.navigateTo({
        url: `../web/index?id=${param}&name=${targetFile[key].name}`,
      })
      return
    }


    this.setData({
      loading: true
    })


    const fs = wx.getFileSystemManager()
    wx.getStorage({
      key: `file${param}`,
      success(res) {
        wx.openDocument({
          filePath: res.data.path,
          fileType: res.data.type, // 根据文件类型设置
          success: function (res) {
            self.setData({
              loading: false
            })
            //console.log('文档打开成功',res);
          },
          fail: function (err) {
            console.error('文档打开失败', err);
            wx.showToast({
              title: '文档打开失败',
            })
          }
        });
      },
      async fail() {
        let session = wx.getStorageSync('session')
        console.log(session)
        try {
          let res = await request.queryFile({
            id: param
          }, session)
          console.log(res)
          let info = res.data.records[0]
          let filePath = info.fileIlk == "" ? wx.env.USER_DATA_PATH + `/${info.name}.docx` : wx.env.USER_DATA_PATH + `/${info.name}.${info.fileIlk}`
          console.log(filePath)
          fs.writeFile({
            filePath: filePath,
            data: wx.base64ToArrayBuffer(res.data.records[0].content), // 确保这是正确的二进制数据或编码后的字符串  
            encoding: "binary",
            success: function (writeRes) {
              console.log("成功写入文件", writeRes);
              wx.setStorageSync(`file${res.data.records[0].id}`, {
                path: filePath,
                type: res.data.records[0].fileIlk
              })
              wx.openDocument({
                filePath: filePath,
                fileType: res.data.records[0].fileIlk, // 根据文件类型设置
                success: function (res) {
                  self.setData({
                    loading: false
                  })
                  //console.log('文档打开成功',res);
                },
                fail: function (err) {
                  console.error('文档打开失败', err);
                  wx.showToast({
                    title: '文档打开失败',
                  })
                }
              });
            },
            fail: function (err) {
              //console.error("写入文件失败", err);  
            }
          })
        } catch (err) {
          self.setData({
            loading: false
          })
          wx.showToast({
            title: '文档打开失败',
            icon: "none"
          })
        }
      }
    })

  },
  enterSearch(e) {
    wx.navigateTo({
      url: '/pages/search/index',
    })
  },
  async onLoad(options) {
    //if(this.data.hasShow) return

    let {
      typeArr,
      go,
      icon
    } = options
    //console.log(go)
    typeArr = typeArr.split(',')
    let typeStr = typeArr.join('_')
    this.setData({
      fatherTypeArr: typeArr,
      fatherType: typeStr,
      go: go,
      icon:icon
    })
    console.log(this.data.fatherType)
    this.setData({
      hasShow: true
    })
    this.setData({
      file: []
    })
    let isFolder = false

    isFolder = await this.getFolder(options.id)
    console.log("isFolder", isFolder)
    if (isFolder) return
    this.getfileInfo("", typeStr)
  },
  onShow() {
    //console.log("onshow",this.data.go,this.data.fatherTypeArr)
    if (!this.data.go) {
      let arr = this.data.fatherTypeArr
      arr.pop()
      this.setData({
        fatherTypeArr: arr
      })
      console.log("onshow", this.data.fatherTypeArr)
    }
  },
  async getfileInfo(isFavour, typeName) {
    this.setData({
      loadingMore: true,
      loadText: "加载更多..."
    });
    let session = wx.getStorageSync('session')

    //let strat = (this.data.current - 1) * this.data.pageSize
    //let pageSize = this.data.pageSize
    let res;
    console.log(typeName)
    if (isFavour) {
      res = await request.listFilePro({
        current: 1,
        pageSize: 80,
        fileType: typeName
      }, session)
      //console.log(res)
      this.setData({
        file: res.data.records
      })
      console.log(this.data.file)
      this.setData({
        loadingMore: false,
        loadText: ""
      });

      return
    }

    res = await request.listFilePro({
      current: this.data.current,
      pageSize: 80,
      fileType: typeName
    }, session)


    console.log(res)
    let arr = []
    arr = JSON.parse(JSON.stringify(this.data.file))
    if (res.code == 0) {
      if (res.data.records.length > 0) {
        this.setData({
          search: true
        })

      }
      for (const item of res.data.records) {
        arr.push(item)
      }
      this.setData({
        file: arr
      })
      //console.log(res.data.total, this.data.file)
      this.setData({
        loadingMore: false,
      });
    } else {
      this.setData({
        loadText: "加载失败"
      });
      // setTimeout(() => {
      //   this.setData({
      //     loadingMore: false
      //   });
      // }, 300)
    }
  },
  async handleFavour(event) {
    console.log(event.currentTarget)
    const param = event.currentTarget.dataset.param
    let session = wx.getStorageSync('session')
    console.log(param)
    let res = await request1.favourFile({
      fileId: param
    }, session)
    console.log(res)
    if (res.code === 0) {
      if (res.data == 1) {
        this.getfileInfo(true, this.data.fatherType)
        wx.showToast({
          title: "收藏成功",
        })
      } else {
        wx.showToast({
          title: '取消收藏成功',
          icon: "none"
        })
      }
    } else {
      wx.showToast({
        title: '收藏失败',
        icon: "none"
      })
    }

  },
  deduplication(arr) {
    arr.forEach((item, index) => {
      if (index < arr.length - 1) {
        if (arr.includes(item, index + 1)) {
          arr.splice(index, 1)
        }
      }

    })
    return arr
  },
  handleClick(e) {
    let index = e.currentTarget.dataset.id
    let {
      id,
      typeName,
      
    } = this.data.folderList[index]
    let arr = []
    arr = this.data.fatherTypeArr
    console.log(arr,)
    arr = this.deduplication(arr)
    arr.push(typeName)
    this.setData({
      go: false
    })
    console.log(id, arr)
    wx.navigateTo({
      url: `../index/index?id=${id}&typeName=${typeName}&typeArr=${arr}&go=true`,

    })
  },
  async getFolder(id) {
    let session = wx.getStorageSync('session')
    try {
      let res = await request2.getSecondFolder({
        PType: id
      }, session)

      console.log(res)
      if (res.code === 0) {

        if (res.data.length) {
          this.setData({
            folderList: res.data
          })
          return true
        }

      }
    } catch (err) {
      console.log(err)
      wx.showToast({
        title: '获取失败',
        icon: "none"
      })
    }

  },
})